const request = require('request');
const express = require("express");
const path = require('path');

const app = express();
const AK = "4Lm3c3Ha82KqxzfbEck8U24X";
const SK = "gUJnJDxCuljpETZbkpZiMmhSJUvcldL4";
let access_token = null;

// 导入 body-parser中间件解析表单数据
const bodyParser = require("body-parser");
app.use(bodyParser.json({ limit: '500mb' }));
app.use(bodyParser.text({ limit: '500mb' }));
app.use(bodyParser.urlencoded({ limit: '500mb', extended: false }));

app.use(express.static(path.join(__dirname, 'public')));

app.get('/', (req, res) => {
  res.setHeader('Content-Type', 'text/html');
  res.sendFile(__dirname + '/public/index.html');
});

// 设置跨域
app.all('*', function (req, res, next) {
  res.setHeader("Access-Control-Allow-Origin", "*");
  res.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
  res.setHeader("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
  res.setHeader('Content-Type', 'application/json');
  next();
});

app.post("/sendMessage", (req, res) => {
  let { message: content } = req.body;
  getAiRes(content, res);
});

app.listen(3000, () => { });

getAccessToken();

function getAiRes(content, res) {
  let options = {
    method: 'POST',
    url: 'https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions_pro?access_token=' + access_token,
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      message: [{
        role: 'user',
        content: content
      }],
      temperature: 0.95,
      top_p: 0.8,
      penalty_score: 1,
      disable_search: false,
      enable_citation: false
    })
  };

  request(options, (error, response) => {
    if (error) {
      res.send({ error: error });
    } else {
      res.send(JSON.parse(response.body));
    }
  });
}

function getAccessToken() {
  let options = {
    method: "POST",
    url: "http://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=" + AK + "&client_secret=" + SK
  };
  request(options, (error, response) => {
    access_token = JSON.parse(response.body).access_token;
    console.log(access_token);
  });
}